package com.supermap.originTest;


import com.supermap.data.*;
import com.supermap.data.conversion.*;

import java.io.*;
import java.sql.Connection;
import java.sql.DriverManager;
import java.sql.PreparedStatement;
import java.sql.ResultSet;
import java.text.SimpleDateFormat;
import java.time.LocalDateTime;
import java.time.format.DateTimeFormatter;
import java.util.*;

public class TestOracle {
    static String LOG_FILE_PATH = "check_" + getCurentDate() + ".log"; // 日志文件路径

    public static void main(String[] args) {

        test();
    }

    public static void test() {
        DatasourceConnectionInfo connectionInfo = new DatasourceConnectionInfo();
     connectionInfo.setEngineType(EngineType.ORACLEPLUS);
       String server = "127.0.0.1:1521/ORCl";
       connectionInfo.setServer(server);
        connectionInfo.setUser("dbtest");
        connectionInfo.setPassword("Bigdata@12");
        connectionInfo.setAlias("ttttqq");

       /* connectionInfo.setEngineType(EngineType.UDBX);
        connectionInfo.setServer("D:\\广西不动产\\租户坐标丢失问题\\test.udbx");
        connectionInfo.setAlias("tttt" + System.currentTimeMillis());*/
        try {
            Workspace wo = new Workspace();
            Datasource datasource = wo.getDatasources().open(connectionInfo);
            System.out.println(datasource.getDatasets().getCount());
            for (int i = 0; i < datasource.getDatasets().getCount(); i++) {
                Dataset dataset = datasource.getDatasets().get(i);
                //if (dataset.getPrjCoordSys().getEPSGCode()>0) {
                dataset.setReadOnly(false);
                System.out.println(dataset.getName() + ",修改前： " + dataset.getPrjCoordSys().getEPSGCode());
                dataset.setPrjCoordSys(PrjCoordSys.fromEPSG(4525));
                System.out.println(dataset.getName() + ",修改后： " + dataset.getPrjCoordSys().getEPSGCode());

                    //考虑先cp到内存设置后再cp回去test
                 /*   Datasource datasource1=openMomeryDatasource(wo);
                    String datasetname=dataset.getName();
                    String nametmp=dataset.getName()+System.currentTimeMillis();

                    System.out.println(dataset.getName() + ",zb： " + dataset.getPrjCoordSys().getEPSGCode());
                    datasource1.copyDataset(dataset,nametmp,EncodeType.NONE);
                    datasource1.getDatasets().get(nametmp).setPrjCoordSys(PrjCoordSys.fromEPSG(4525));
                    datasource.getDatasets().delete(datasetname);
                    datasource.copyDataset(datasource1.getDatasets().get(nametmp),datasetname,EncodeType.NONE);*/

                }
            //}
            wo.save();
            wo.dispose();
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
            ex.printStackTrace();
        }
        System.out.println(" 修改OK");
    }

    public static void modifyDatasetCoor(String oraName, String user) {
        DatasourceConnectionInfo connectionInfo = new DatasourceConnectionInfo();
        connectionInfo.setEngineType(EngineType.ORACLEPLUS);
        String server = "6.6.8.200:1521/QJ" + oraName;
        connectionInfo.setServer(server);
        connectionInfo.setUser(user);
        connectionInfo.setPassword("gtt123456");
        connectionInfo.setAlias(oraName + "_" + user + "_" + System.currentTimeMillis());

        Map<String, Integer> epsgCodes = new HashMap<>();  //定义坐标集合存储水平偏移量、中央经线对应的epsgcode值
        epsgCodes.put("34500000-102", 4522);
        epsgCodes.put("35500000-105", 4523);
        epsgCodes.put("36500000-108", 4524);
        epsgCodes.put("37500000-111", 4525);
        epsgCodes.put("38500000-114", 4526);
        epsgCodes.put("500000-102", 4543);
        epsgCodes.put("500000-105", 4544);
        epsgCodes.put("500000-108", 4545);
        epsgCodes.put("500000-111", 4526);
        epsgCodes.put("500000-114", 4527);
        Workspace wo = new Workspace();
        try {
            Datasource datasource = wo.getDatasources().open(connectionInfo);
            for (int i = 0; i < datasource.getDatasets().getCount(); i++) {
                Dataset dataset = datasource.getDatasets().get(i);
                if (dataset.getPrjCoordSys() == null) {
                    //myoutput.output("当前坐标为空，请检查！ server：" +server +",user:" +user+",数据集："+dataset.getName());
                    System.out.println("PrjCoordSys()==null " + dataset.getName());
                    return;
                }
                PrjCoordSys prjCoordSys = dataset.getPrjCoordSys();
                String falseEasting = "";
                String center = "";
                String spheroid = "";
                String horizontalGeodeticDatum = "";
                System.out.println(datasource.getPrjCoordSys().getEPSGCode());
                if (dataset.getPrjCoordSys().getEPSGCode() <= 0) {
                    dataset.setReadOnly(false);
                    System.out.println(dataset.getName() + ",修改前： " + dataset.getPrjCoordSys().getEPSGCode());
                    System.out.println(datasource.getPrjCoordSys().getEPSGCode());
                    dataset.setPrjCoordSys(PrjCoordSys.fromEPSG(4525));
                    datasource.refresh();
                    System.out.println(dataset.getName() + ",修改后： " + dataset.getPrjCoordSys().getEPSGCode());
                }

             /*   if (!dataset.getPrjCoordSys().getName().contains("Planar")) {
                    if (dataset.getPrjCoordSys().getEPSGCode() <= 0) {
                        falseEasting = prjCoordSys.toXML().toString().split("FalseEasting")[1].split(">")[1].split("<")[0];
                        center = prjCoordSys.toXML().toString().split("CentralMeridian")[1].split(">")[1].split("<")[0];
                        spheroid = prjCoordSys.toXML().toString().split("Spheroid")[1].split("sml:Name")[1].split(">")[1].split("<")[0];
                        horizontalGeodeticDatum = prjCoordSys.toXML().toString().split("HorizontalGeodeticDatum")[1].split("sml:Name")[1].split(">")[1].split("<")[0];
                        if (spheroid.contains("2000") && horizontalGeodeticDatum.contains("2000")) {

                           *//* String key = falseEasting + "-" + center;
                            Integer epsgCode = epsgCodes.get(key);
                            if (epsgCode != null) {
                                dataset.setReadOnly(false);
                                System.out.println(dataset.getName() + ",修改前： " + dataset.getPrjCoordSys().getEPSGCode());
                                dataset.setPrjCoordSys(PrjCoordSys.fromEPSG(epsgCode));
                                datasource.refresh();
                                wo.save();
                                System.out.println(dataset.getName() + ",修改后： " + dataset.getPrjCoordSys().getEPSGCode());
                            }*//*
                        }
                    }
                }
                wo.save();*/
            }
            wo.save();
            wo.dispose();

        } catch (Exception ex) {
            System.out.println("打开数据源失败 : " + ex.getMessage() + ",连接信息server:+" + server + ",user:" + user);
        }
        System.out.println("modify ok");

    }

    public static void backupDatasetCoor(String oraName, String user, Datasource datasourcetmp) {
        //打开oracel数据源
        DatasourceConnectionInfo connectionInfo = new DatasourceConnectionInfo();
        connectionInfo.setEngineType(EngineType.ORACLEPLUS);
        String server = "6.6.8.200:1521/QJ" + oraName;
        connectionInfo.setServer(server);
        connectionInfo.setUser(user);
        connectionInfo.setPassword("gtt123456");
        connectionInfo.setAlias(oraName + "_" + user + "_" + System.currentTimeMillis());

        Workspace workspace = new Workspace();


        try {
            Datasource datasource = workspace.getDatasources().open(connectionInfo);
            for (int i = 0; i < datasource.getDatasets().getCount(); i++) {
                Dataset dataset = datasource.getDatasets().get(i);
                if (dataset.getPrjCoordSys() == null) {
                    //myoutput.output("当前坐标为空，请检查！ server：" +server +",user:" +user+",数据集："+dataset.getName());
                    System.out.println("PrjCoordSys()==null " + dataset.getName());
                    return;
                }
                PrjCoordSys prjCoordSys = dataset.getPrjCoordSys();
                if (dataset.getPrjCoordSys().getEPSGCode() <= 0) {

                    if (dataset.getPrjCoordSys().getEPSGCode() <= 0) {
                        DatasetVector datasetVector_result = null;
                        DatasetVectorInfo datasetInfotemp = new DatasetVectorInfo();
                        datasetInfotemp.setName("Zh_" + oraName + "_user_" + user + "_" + dataset.getName());
                        datasetInfotemp.setType(DatasetType.REGION);
                        datasetInfotemp.setEncodeType(EncodeType.NONE);
                        Dataset datasettmp = datasourcetmp.getDatasets().create(datasetInfotemp);
                        datasettmp.setPrjCoordSys(prjCoordSys);
                    }

                }


            }

        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        System.out.println("OK");

    }

    /**
     * 创建udb数据源
     * Create UDBX datasource
     */
    public static Datasource createDatasourceUdbPlus(Workspace workspace, String path, String database) {
        try {
            DatasourceConnectionInfo info = new DatasourceConnectionInfo();
            info.setEngineType(EngineType.UDBX);
            info.setAlias(database);
            info.setServer(path + "/" + database);
            Datasource ds = workspace.getDatasources().create(info);
            return ds;
        } catch (Exception ex) {
            System.out.println("create datasource has error +" + ex.getMessage());
            return null;
        }
    }

    public static String GeometryToGeoJson(Geometry geometry) {
        String result = "";
        // geometry 转dataset
        Datasource datasource = openMomeryDatasource(new Workspace());
        Dataset dataset = datasetCreateByGeometry(datasource, "tmp" + System.currentTimeMillis(), geometry);
        ExportSettingGeoJson exportSettingGeoJson = new ExportSettingGeoJson();
        exportSettingGeoJson.setSourceData(dataset);
        exportSettingGeoJson.setTargetFileType(FileType.GEOJSON);

        DataExport export = new DataExport();
        export.getExportSettings().add(exportSettingGeoJson);
        try {
            ExportResult resultEx = export.run();
            if (resultEx.getFailedSettings().length == 0) {
                //导出geojson成功
                System.out.println(1111);

            }
        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }
        return result;
    }



    public static String removeInvalidCharacters(String jsonStr) {
        StringBuilder sb = new StringBuilder();
        for (char c : jsonStr.toCharArray()) {
            // ASCII printable characters range from 32 to 126 inclusive
            if ((c >= 32 && c <= 126) || c == '\n' || c == '\r' || c == '\t') {
                sb.append(c);
            }
        }
        return sb.toString();
    }

    private static String cleanJsonString(String path) {
        String geoJsonString = "";
        String cleanedJsonString = "";
        try {
            geoJsonString = readFileToString(path);
            String jsonString = removeInvalidCharacters(geoJsonString);
            // 移除数字与数字之间的非法字符（如乱码字符、空格）
            String cleanedJsonStringTmp = jsonString.replaceAll("(?<=\\d)[^\\d.,]*(?=\\d)", "");
            // 移除多余的空格
            cleanedJsonString = cleanedJsonStringTmp.replaceAll("\\s+", " ").trim();

        } catch (IOException e) {
            e.printStackTrace();
        }
        return cleanedJsonString;
    }

    /***
     * json 多部件四层转arcgis三层
     * @param  四层json 注意乱码要清洗
     * @return
     */

    // 示例方法：读取文件内容到String
    public static String readFileToString(String filePath) throws IOException {
        StringBuilder contentBuilder = new StringBuilder();
        try (BufferedReader br = new BufferedReader(new FileReader(filePath))) {
            String sCurrentLine;
            while ((sCurrentLine = br.readLine()) != null) {
                contentBuilder.append(sCurrentLine).append("\n");
            }
        }
        return contentBuilder.toString();
    }


    private static String buildFilePath(String directory, String fileName) {
        // 使用File.separator来确保路径的跨平台兼容性
        return directory + File.separator + fileName;
    }

    public static void testMAPdele() {

        writeLog("\n");
        writeLog("开始验证...");
        //打开工作空间
        WorkspaceConnectionInfo workspaceConnectionInfo = new WorkspaceConnectionInfo();
        workspaceConnectionInfo.setType(WorkspaceType.PGSQL);
        workspaceConnectionInfo.setServer("127.0.0.1:5432");
        workspaceConnectionInfo.setDriver("PGSQL");
        workspaceConnectionInfo.setDatabase("hhl44");
        workspaceConnectionInfo.setUser("postgres");
        workspaceConnectionInfo.setPassword("AMWngjvo1314");
        workspaceConnectionInfo.setName("hhl442");
        try {
            Workspace workspace = new Workspace();
            //System.out.println("version  :" + workspace.getVersion());
            String v = workspace.getVersion().name();
            workspace.open(workspaceConnectionInfo);
            Maps maps = workspace.getMaps();  //获取当前maps集合存到对比txt
            maps.addRemovedListener(steppedEvent -> {
                System.out.println(getCurentTime() + steppedEvent.getMapName() + "Removed.....");
            });

            maps.addRemovingListener(steppedEvent -> {
                System.out.println(getCurentTime() + steppedEvent.getMapName() + "Removing.....");
            });

            maps.addRenamedListener(steppedEvent -> {
                System.out.println(getCurentTime() + " Renamed.....");
            });
            maps.addRenamingListener(steppedEvent -> {
                System.out.println(getCurentTime() + "Renaming.....");
            });
            maps.remove(1);
            Thread.sleep(5000);
            maps.remove(1);

        } catch (Exception ex) {
            writeLog("检查异常：" + ex.getMessage());
        }


        writeLog("检查结束.");
    }

    public static Dataset createDataset(Datasource datasource, String tempDtName, Recordset recordset, DatasetVector datasetVector_temp) {
        DatasetVectorInfo datasetInfo = new DatasetVectorInfo(tempDtName, datasetVector_temp);
        if (datasource != null) {
            if (datasource.getDatasets().contains(tempDtName)) {
                DatasetVector datasetVector = (DatasetVector) datasource.getDatasets().get(tempDtName);
                datasetVector.truncate();
                datasetVector.append(recordset);
                return datasetVector;
            }
            Dataset dataset = datasource.getDatasets().create(datasetInfo);
            //设置默认坐标系
            dataset.setPrjCoordSys(recordset.getDataset().getPrjCoordSys());
            DatasetVector datasetVector = (DatasetVector) dataset;
            ArrayList<String> sourceFieldNames1 = new ArrayList<>();
            FieldInfos srcFieldInfos1 = datasetVector_temp.getFieldInfos();
            for (int i = 0; i < srcFieldInfos1.getCount(); i++) {
                FieldInfo srcFieldInfo = srcFieldInfos1.get(i);
                if (srcFieldInfo.isSystemField() || srcFieldInfo.getName().equalsIgnoreCase("smuserid")) {
                    continue;
                }
                sourceFieldNames1.add(srcFieldInfo.getName());
                datasetVector.getFieldInfos().add(srcFieldInfo.clone());
            }
            if (datasetVector.append(recordset)) {
                recordset.close();
                recordset.dispose();
                return dataset;
            }
            return null;
        } else {
            return null;
        }
    }


    public static Dataset datasetCreateByGeometry(Datasource datasource, String datasetname, Geometry geometry) {
        Dataset dataset;
        //如果存在删除
        if (datasource.getDatasets().get(datasetname) != null) {
            try {
                boolean b1 = datasource.getDatasets().delete(datasetname);
            } catch (Exception ex) {
            }
        }
        DatasetVectorInfo datasetVectorInfo = new DatasetVectorInfo();
        datasetVectorInfo.setType(DatasetType.REGION);
        datasetVectorInfo.setFileCache(false);
        datasetVectorInfo.setName(datasetname);
        // 创建矢量数据集 线
        dataset = datasource.getDatasets().create(datasetVectorInfo);
        DatasetVector datasetVector = (DatasetVector) dataset;
        Recordset recordset = datasetVector.getRecordset(false, CursorType.DYNAMIC);
        recordset.getBatch().begin();
        recordset.addNew(geometry);
        recordset.getBatch().update();
        recordset.close();
        recordset.dispose();
        return dataset;
    }


    /***
     * 柳州自然资源基础信息平台一期检查postgres工作空间内的是否异常
     */
    private static void checkPostgreWorkspaceMap() {
        String baseDirectory = "checklogs"; // 存放检查结果日志
        createDirectoryIfNotExists(baseDirectory);
        String fileName = LOG_FILE_PATH;
        // 构建文件路径
        String filePath = buildFilePath(baseDirectory, fileName);
        LOG_FILE_PATH = filePath;
        System.out.println(getCurentTime() + " 开始检查....");
        checkMap();
        System.out.println(getCurentTime() + " 检查结束.");
        // 执行完毕后退出
        try {
            Thread.sleep(2000);
        } catch (InterruptedException e) {
            e.printStackTrace();
        }
        System.exit(0);
    }

    private static void createDirectoryIfNotExists(String directoryPath) {
        // 创建 File 对象
        File directory = new File(directoryPath);
        // 检查文件夹是否已经存在
        if (!directory.exists()) {
            // 尝试创建文件夹
            boolean isCreated = directory.mkdir();
            // 检查文件夹是否成功创建
            if (isCreated) {
            } else {
                System.out.println("无法创建文件夹 " + directory.getAbsolutePath() + "。");
            }
        } else {
        }
    }

    public static void checkMap() {

        writeLog("\n");
        writeLog("开始检查...");
        // 文件路径
        String baseDirectory2 = "workspace"; // 工作空间地图文件
        createDirectoryIfNotExists(baseDirectory2);
        //System.out.println("version  :" + v);
        //打开工作空间
        WorkspaceConnectionInfo workspaceConnectionInfo = new WorkspaceConnectionInfo();
        workspaceConnectionInfo.setType(WorkspaceType.PGSQL);
        workspaceConnectionInfo.setServer("127.0.0.1:5432");
        workspaceConnectionInfo.setDriver("PGSQL");
        workspaceConnectionInfo.setDatabase("hhl44");
        workspaceConnectionInfo.setUser("postgres");
        workspaceConnectionInfo.setPassword("AMWngjvo1314");
       /* workspaceConnectionInfo.setServer("199.225.168.84:5432");
        workspaceConnectionInfo.setDriver("PGSQL");
        workspaceConnectionInfo.setDatabase("sgs_digicity_mds");
        workspaceConnectionInfo.setUser("sgs_digicity_mds");
        workspaceConnectionInfo.setPassword("Sagis@123456");*/
        List<String> listw = getWorkspaceName();
        for (String workspacename : listw) {
            workspaceConnectionInfo.setName(workspacename);
            try {
                Workspace workspace = new Workspace();
                //System.out.println("version  :" + workspace.getVersion());
                String v = workspace.getVersion().name();
                workspace.open(workspaceConnectionInfo);
                Maps maps = workspace.getMaps();  //获取当前maps集合存到对比txt
                List<String> list = new ArrayList<>();
                for (int i = 0; i < maps.getCount(); i++) {
                    list.add(maps.get(i).toString());
                }
                String filePathtmp = workspacename + ".txt";
                String filePath = buildFilePath(baseDirectory2, filePathtmp);
                // 检查文件是否存在
                File file = new File(filePath);
                List<String> fileContent = new ArrayList<>();
                if (!file.exists()) {
                    // 文件不存在，将整个List写入文件
                    writeListToFile(list, filePath);
                } else {
                    // 文件存在，读取文件内容
                    try (BufferedReader reader = new BufferedReader(new FileReader(file))) {
                        String line;
                        while ((line = reader.readLine()) != null) {
                            fileContent.add(line);
                        }
                    } catch (IOException e) {
                        e.printStackTrace();
                        writeLog("读取文件内容异常：" + e.getMessage());
                        return;
                    }
                    // 对比List和文件内容，找出新增的元素
                    List<String> newItems = new ArrayList<>(list);
                    newItems.removeAll(fileContent);
                    // 如果有新增元素，则写入文件
                    if (!newItems.isEmpty()) {
                        appendListToFile(newItems, filePath);
                    }
                    // 对比List和文件内容，找出新增和删减的元素
                    fileContent.removeAll(list);
                    // 输出删减的元素到app.log日志
                    if (!fileContent.isEmpty()) {
                        String result = String.join(", ", fileContent);
                        writeLog("工作空间{" + workspacename + "}被删除地图名称{ " + result + " }");
                    }
                }
                workspace.close();
                workspace.dispose();
            } catch (Exception ex) {
                writeLog("检查异常：" + ex.getMessage());
            }

        }
        writeLog("检查结束.");
    }

    // 将整个List写入文件（如果文件已存在，则会被覆盖）
    private static void writeListToFile(List<String> list, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath))) {
            for (String item : list) {
                writer.write(item);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
            writeLog("写入文件异常：" + e.getMessage());
        }
    }

    // 将List中的元素追加到文件末尾
    private static void appendListToFile(List<String> list, String filePath) {
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(filePath, true))) {
            for (String item : list) {
                writer.write(item);
                writer.newLine();
            }
        } catch (IOException e) {
            e.printStackTrace();
            writeLog("元素追加到文件末尾异常：" + e.getMessage());
        }
    }

    public static List<String> getWorkspaceName() {
        List<String> list = new ArrayList<>();

        String URL = "jdbc:postgresql://127.0.0.1:5432/hhl44";
        String USER = "postgres";
        String PASSWORD = "AMWngjvo1314";
     /*   String URL = "jdbc:postgresql://199.225.168.84:5432/sgs_digicity_mds";
        String USER = "sgs_digicity_mds";
        String PASSWORD = "Sagis@123456";*/
        try {
            // 1.加载驱动
            Class.forName("org.postgresql.Driver");
            // 2.获取连接
            Connection connection = DriverManager.getConnection(URL, USER, PASSWORD);
            // 3.创建Statement对象（可以执行sql的对象）
            PreparedStatement preparedStatement = connection.prepareStatement("SELECT smworkspacename \n" +
                    "FROM sdx.smworkspace;");
            // 4.获取结果集
            ResultSet resultSet = preparedStatement.executeQuery();
            // 5.对数据进行处理
            while (resultSet.next()) {
                //Integer id = resultSet.getInt("SMID");
                String workspacename = resultSet.getArray("smworkspacename").toString();
                list.add(workspacename);
            }

        } catch (Exception ex1) {
            writeLog("取工作空间名称异常：" + ex1.getMessage());
        }
        return list;

    }

    //格式化当前时间
    public static String getCurentDate() {
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 定义日期时间格式（例如：yyyy-MM-dd HH:mm:ss）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyyMMdd");
        // 格式化并输出时间
        String formattedTime = currentTime.format(formatter);
        return formattedTime;
    }


    // 写入日志的方法
    public static void writeLog(String path, String message) {
        // 定义时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String formattedDate = sdf.format(new Date());
        // 日志级别
        String level = "INFO";
        // 完整的日志信息
        String logMessage = "";
      /*  if (message == "\n") {
            logMessage = String.format("", "", "", message);
        } else {
            logMessage = String.format("%s [%s] %s%n", formattedDate, level, message);
        }*/
        logMessage = message;
        // 写入文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(path, true))) {
            writer.write(logMessage);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

    }

    // 写入日志的方法
    public static void writeLog(String message) {
        // 定义时间格式
        SimpleDateFormat sdf = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss.SSS");
        String formattedDate = sdf.format(new Date());
        // 日志级别
        String level = "INFO";
        // 完整的日志信息
        String logMessage = "";
        if (message == "\n") {
            logMessage = String.format("", "", "", message);
        } else {
            logMessage = String.format("%s [%s] %s%n", formattedDate, level, message);
        }
        // 写入文件
        try (BufferedWriter writer = new BufferedWriter(new FileWriter(LOG_FILE_PATH, true))) {
            writer.write(logMessage);
        } catch (IOException e) {
            e.printStackTrace();
            System.out.println(e.getMessage());
        }

    }

    public static void testOracleZB() {
        Workspace workspace = new Workspace();
        String v = workspace.getVersion().name();
        System.out.println("version  :" + v);
        //打开工作空间
        WorkspaceConnectionInfo workspaceConnectionInfo = new WorkspaceConnectionInfo();
        workspaceConnectionInfo.setType(WorkspaceType.SMWU);
        workspaceConnectionInfo.setServer("D:\\广西不动产\\问题\\WorkSpace2.smwu");
        try {
            workspace.open(workspaceConnectionInfo);
           /* for(int i=0;i<workspace.getDatasources().getCount();i++)
            {
                System.out.println("数据源名字: " +workspace.getDatasources().get(i).getAlias());
            }*/
            Datasource datasource = workspace.getDatasources().get("supermap");

            Dataset dataset = datasource.getDatasets().get("test_4524_zj");
            Dataset dataset1 = datasource.getDatasets().get("test_4524_zj_1");
            System.out.println("设置坐标前坐标： " + dataset1.getPrjCoordSys().getEPSGCode());
            dataset1.setPrjCoordSys(PrjCoordSys.fromEPSG(4490));
            System.out.println("设置坐标后坐标： " + dataset1.getPrjCoordSys().getEPSGCode());


            DatasetVector datasetVector = (DatasetVector) dataset;

            System.out.println("删除前记录: " + datasetVector.getRecordCount());
            //String sql="name in ('2','5','6')";
            String sql = "SMID>0 AND SMID<1000";
            Recordset recordset = datasetVector.query(sql, CursorType.DYNAMIC);
            System.out.println("recordset.getRecordCount(): " + recordset.getRecordCount());

            recordset.deleteAll();

            System.out.println("删除后记录: " + datasetVector.getRecordCount());

            String name = "xg";
            Datasource datasourceMemeroy = openMomeryDatasource(workspace);
            //导入到指定数据源的数据集中
            ImportSettingSHP importSettingSHP = new ImportSettingSHP();
            importSettingSHP.setAttributeIgnored(false);
            //设置当同名数据集存在时导入的模式,如果存在名字冲突，则覆盖
            importSettingSHP.setImportMode(ImportMode.OVERWRITE);
            //设置需要导入的数据路径信息
            importSettingSHP.setSourceFilePath("D:\\广西不动产\\租户坐标丢失问题\\testdata\\DT.shp");
            importSettingSHP.setImporttingAs3D(false);
            importSettingSHP.setImportMode(ImportMode.NONE);
            importSettingSHP.setTargetEncodeType(EncodeType.NONE);
            //设置需要导入的数据编码类型，因为有中文字段，所以用ASCII编码
            importSettingSHP.setSourceFileCharset(Charset.ANSI);
            //设置要导入的目标数据源
            importSettingSHP.setTargetDatasource(datasourceMemeroy);
            //设置目标数据集名称
            importSettingSHP.setTargetDatasetName(name);
            DataImport importer = new DataImport();
            importer.getImportSettings().add(importSettingSHP);
            try {
                ImportResult result = importer.run();
                if (result.getFailedSettings().length == 0) {
                    System.out.println("导入成功！");
                    DatasetVector datasetVector1 = (DatasetVector) datasourceMemeroy.getDatasets().get(name);
                    PrjCoordSys prjCoordSys = datasetVector1.getPrjCoordSys();
                    System.out.println(datasetVector1.getPrjCoordSys().getName());
                    // String projectionHeight= prjCoordSys.toXML().toString().split("ProjectionHeight")[1].split(">")[1].split("<")[0];
                    // String  falseEasting=prjCoordSys.toXML().toString().split("FalseEasting")[1].split(">")[1].split("<")[0];
                    // String  center=prjCoordSys.toXML().toString().split("CentralMeridian")[1].split(">")[1].split("<")[0];
                    // String  inverseFlattening=prjCoordSys.toXML().toString().split("InverseFlattening")[1].split(">")[1].split("<")[0];

                    Recordset recordset_temp = datasetVector1.getRecordset(false, CursorType.STATIC);
                    if (recordset_temp.getRecordCount() > 0) {
                      /*  System.out.println("append的记录数：  " + recordset_temp.getRecordCount());
                        System.out.println("追加前记录： "+datasetVector.getRecordCount());
                        boolean b = datasetVector.append(recordset_temp);  //现在工程代码不用这个append反而用recordset.addNew性能更差。
                        if (!b) {
                            System.out.println("追加失败");
                        }
                        else
                        {
                            System.out.println("追加成功。追加后记录： "+datasetVector.getRecordCount());

                        }*/
                        System.out.println("追加前记录： " + datasetVector.getRecordCount());
                        System.out.println("addNew记录数：  " + recordset_temp.getRecordCount());
                        boolean f = inSertRecordset(datasetVector, recordset_temp);
                        if (!f) {
                            System.out.println("追加失败");
                        } else {
                            System.out.println("追加成功。追加后记录： " + datasetVector.getRecordCount());

                        }
                    }
                }
            } catch (Exception ex1) {
                System.out.println("异常！ " + ex1.getMessage());

            }


        } catch (Exception ex) {
            System.out.println(ex.getMessage());
        }


        //打开oracel数据源

       /* DatasourceConnectionInfo connectionInfo = new DatasourceConnectionInfo();
        connectionInfo.setEngineType(EngineType.ORACLEPLUS);
        connectionInfo.setServer("127.0.0.1:1521/orcl");
        connectionInfo.setUser("supermap");
        connectionInfo.setPassword("supermap");
        //connectionInfo.setDatabase("orcl");
        connectionInfo.setAlias("ORCL223");
        Workspace workspace = new Workspace();

        try {
            Datasource datasource = workspace.getDatasources().open(connectionInfo);
            System.out.println("数据集1名字: " + datasource.getDatasets().get(0).getName());

        } catch (Exception ex) {
            System.out.println("open fail : " + ex.getMessage());
        }*/


    }

    public static boolean inSertRecordset(DatasetVector datasetVector, Recordset recordset) {
        boolean f = false;
        //获取记录集
        Recordset recordset_result = datasetVector.getRecordset(false, CursorType.DYNAMIC);
        recordset_result.getBatch().setMaxRecordCount(500);
        recordset_result.getBatch().begin();

        while (!recordset.isEOF()) {
            Geometry geometry = recordset.getGeometry();
            Map map = new HashMap();
            FieldInfos fieldInfos = recordset.getFieldInfos();
            for (int i = 0; i < fieldInfos.getCount(); i++) {
                FieldInfo fieldInfo = fieldInfos.get(i);
                if (!fieldInfo.getName().toLowerCase().startsWith("sm"))
                    map.put(fieldInfo.getName(), recordset.getFieldValue(fieldInfo.getName()));
            }

            recordset_result.addNew(geometry, map);
            geometry.dispose();
            recordset.moveNext();
        }

        // 批量操作统一提交
        try {
            recordset_result.getBatch().update();
            // 释放记录集
            recordset.dispose();
            recordset_result.dispose();
            f = true;
        } catch (Exception ex) {
            System.out.println("recordset update failed");
            f = false;
        }
        return f;
    }

    //格式化当前时间
    public static String getCurentTime() {
        // 获取当前时间
        LocalDateTime currentTime = LocalDateTime.now();
        // 定义日期时间格式（例如：yyyy-MM-dd HH:mm:ss）
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd HH:mm:ss");
        // 格式化并输出时间
        String formattedTime = currentTime.format(formatter);
        return formattedTime;
    }

    /**
     * 创建内存数据源新的11.1.1的内存数据源已经改成了udbx检查下您们项目代码创建的内存数据源是udb还是
     *
     * @return
     */
    public static Datasource openMomeryDatasource(Workspace workspace) {
        if (workspace == null) {
            try {
                workspace = new Workspace();
            } catch (Exception ex) {
                System.out.println("Gis license invalid");
            }
        }
        String name = "MemoryDatasource" + System.currentTimeMillis();
        if (workspace.getDatasources().contains(name)) {
            return workspace.getDatasources().get(name);
        }
        DatasourceConnectionInfo dsConInfo = new DatasourceConnectionInfo();
        //dsConInfo.setServer(":memory:");
        // dsConInfo.setEngineType(EngineType.UDBX);
        dsConInfo.setEngineType(EngineType.MEMORY);  //这个会user_date这种字段异常。确认是否还有其他异常。产品在哪一个版本修正成了UDBX
        dsConInfo.setAlias(name);
        Datasource ds = workspace.getDatasources().create(dsConInfo);
        return ds;
    }

}
